package com.cl.datasubscription.task;

import com.alibaba.fastjson.JSONObject;
import com.cl.chlorine.dto.CommonResult;
import com.cl.chlorine.util.HttpUtil;
import com.cl.datasubscription.entity.*;
import com.cl.datasubscription.repository.SubscribeTaskDataRecordRepository;
import com.cl.datasubscription.repository.SubscribeTaskExecuteRecordRepository;
import com.cl.datasubscription.repository.SubscribeTaskMailRecordRepository;
import com.cl.datasubscription.schedule.config.SpiderCronTaskRegistrar;
import com.cl.datasubscription.service.SubscribeTaskMailRelationService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class SubscribeKeywordTaskExecutor {
    private final SubscribeTaskMailRelationService subscribeTaskMailRelationService;
//    private final static BlockingQueue<String> dataQueue = new LinkedBlockingDeque<>();

    private final static ConcurrentHashMap<Long, BlockingQueue<String>> dataQueueMap = new ConcurrentHashMap<>();
    private final static AtomicBoolean isRunning = new AtomicBoolean(false);

    private final HttpUtil httpUtil;

    private final static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private final SubscribeTaskExecuteRecordRepository subscribeTaskExecuteRecordRepository;
    private final SubscribeTaskDataRecordRepository subscribeTaskDataRecordRepository;
    private final SubscribeTaskMailRecordRepository subscribeTaskMailRecordRepository;


    public SubscribeKeywordTaskExecutor(SubscribeTaskMailRelationService subscribeTaskMailRelationService, HttpUtil httpUtil,
                                        SubscribeTaskExecuteRecordRepository subscribeTaskExecuteRecordRepository,
                                        SubscribeTaskDataRecordRepository subscribeTaskDataRecordRepository,
                                        SubscribeTaskMailRecordRepository subscribeTaskMailRecordRepository) {
        this.subscribeTaskMailRelationService = subscribeTaskMailRelationService;
        this.httpUtil = httpUtil;
        this.subscribeTaskExecuteRecordRepository = subscribeTaskExecuteRecordRepository;
        this.subscribeTaskDataRecordRepository = subscribeTaskDataRecordRepository;
        this.subscribeTaskMailRecordRepository = subscribeTaskMailRecordRepository;
    }



    public static   CommonResult addData(String data) {
        if (dataQueueMap.isEmpty()) {
            Set<Long> schedulerIds = SpiderCronTaskRegistrar.getSchedulerIds();
            schedulerIds.forEach(id->{
                dataQueueMap.put(id,new LinkedBlockingQueue<>());
            });
        }
        dataQueueMap.values().forEach(dataQueue -> {
            dataQueue.add(data);
        });
        return CommonResult.success(data, "数据加入订阅队列");
    }

    //    @Async("taskScheduler")
//    public void consumer() {
//        if (isRunning.get()) {
//            return;
//        }
//        isRunning.set(true);
//        try {
//            while (true) {
//                String data = dataQueue.poll();
//
//            }
//        } finally {
//            isRunning.set(false);
//        }
//
//    }
    @Async("taskScheduler")
    public void consumer(SubscribeKeywordTask subscribeKeywordTask) {
        SubscribeTaskExecuteRecord subscribeTaskExecuteRecord = new SubscribeTaskExecuteRecord();
        subscribeTaskExecuteRecord.setSubscribeTaskId(subscribeKeywordTask.getId());
        subscribeTaskExecuteRecordRepository.save(subscribeTaskExecuteRecord);

        List<String> matchData = new ArrayList<>();
        String keyword = subscribeKeywordTask.getKeyword();

        dataQueueMap.putIfAbsent(subscribeKeywordTask.getId(), new LinkedBlockingDeque<>());
        BlockingQueue<String> dataQueue = dataQueueMap.get(subscribeKeywordTask.getId());

        for (int i = 0; i < dataQueue.size(); i++) {
            String data = dataQueue.poll();
            if (data.contains(keyword)) {
                matchData.add(data);
            }
        }

        Long subscribeKeywordTaskId = subscribeKeywordTask.getId();
        LocalDateTime now = LocalDateTime.now();
        String subject = now.format(dateTimeFormatter) + " 关键词(" + keyword + ")订阅邮件";
        StringBuilder content = new StringBuilder();
        AtomicInteger count = new AtomicInteger(0);
        List<SubscribeTaskDataRecord> subscribeTaskDataRecordList = new ArrayList<>();
        matchData.forEach(data -> {
            content.append(count.incrementAndGet()).append(". ").append(data).append("<br>");

            SubscribeTaskDataRecord subscribeTaskDataRecord = new SubscribeTaskDataRecord();
            subscribeTaskDataRecord.setSubscribeTaskExecuteRecordId(subscribeTaskExecuteRecord.getId());
            subscribeTaskDataRecord.setDataJson(data);
            subscribeTaskDataRecordList.add(subscribeTaskDataRecord);
        });

        subscribeTaskDataRecordRepository.saveAll(subscribeTaskDataRecordList);


        List<SubscribeTaskMailRelation> relationList = subscribeTaskMailRelationService.findByField("subscribeTaskId", String.valueOf(subscribeKeywordTaskId));
        String[] mails = relationList.stream().map(SubscribeTaskMailRelation::getMail).toList().toArray(new String[0]);
        JSONObject mailParam = new JSONObject();
        mailParam.put("subject", subject);
        mailParam.put("content", content);
        mailParam.put("to", mails);
        mailParam.put("fromName", "关键词订阅服务");


        if (content.isEmpty()) {
            return;
        }
//        Boolean success = httpUtil.okhttpPostBoolean("http://172.16.137.55:8080/email-service/sendMail/send",mailParam);
        Boolean success = httpUtil.okhttpPostBoolean("http://localhost:8080/sendMail/send1", mailParam);

        List<SubscribeTaskMailRecord> subscribeTaskMailRecordList = new ArrayList<>();
        relationList.forEach(relation -> {


            SubscribeTaskMailRecord subscribeTaskMailRecord = new SubscribeTaskMailRecord();
            subscribeTaskMailRecord.setSubscribeTaskMailRelationId(relation.getId());
            subscribeTaskMailRecord.setSubscribeTaskExecuteRecordId(subscribeTaskExecuteRecord.getId());
            subscribeTaskMailRecord.setSuccessFlag(success);
            subscribeTaskMailRecordList.add(subscribeTaskMailRecord);
            System.out.println(relation.getMail());
            System.out.println(subject);
            System.out.println(content);
        });


        subscribeTaskMailRecordRepository.saveAll(subscribeTaskMailRecordList);
        System.out.println();
    }
}
